<template>
  <div class="app-container">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-position="top"
      class="dialogForm"
    >
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item>
            <span slot="label"> 视频 </span>
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :before-upload="handleBeforeUploadVideo"
              :on-success="handleUploadSuccessVideo"
              :on-remove="handleRemoveVideo"
              :headers="headers"
              :before-remove="beforeRemove"
              :limit="1"
              :file-list="videoList"
              :on-exceed="handleExceed"
              accept="video/mp4,video/x-msvideo,video/quicktime"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传mp4文件，且不超过200MB
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col v-if="type == 2" :span="12">
          <el-form-item>
            <span slot="label"> 图片 </span>
            <el-upload
              ref="upload"
              class="upload-demo"
              :action="uploadUrl"
              :before-upload="handleBeforeUpload"
              :on-success="handleUploadSuccess"
              :on-remove="handleRemove"
              :headers="headers"
              :before-remove="beforeRemove"
              :limit="1"
              :file-list="fileList"
              :on-exceed="handleExceed"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col v-if="type == 1" :span="12">
          <el-form-item label="城市" prop="areaName">
            <el-cascader
              v-model="form.areaName"
              :options="cityList"
              :props="{ checkStrictly: true }"
              class="w-100"
              @change="handleChange"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="type == 1" :span="12">
          <el-form-item label="上级">
            <el-input
              v-model="form.parentAreaName"
              readonly
              placeholder="请输入内容"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示顺序" prop="orderNum">
            <el-input v-model="form.orderNum" placeholder="请输入显示顺序" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in statusList"
                :key="dict.value"
                :label="dict.value"
                >{{ dict.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="内容" prop="content">
        <editor v-model="form.content" :min-height="192" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { addData, cityList, getDataById, editData } from "@/api/index";
import { getToken } from "@/utils/auth";
export default {
  name: "Role",
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/uploadPc/policy", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      statusList: [
        {
          value: 1,
          label: "开启",
        },
        {
          value: 0,
          label: "关闭",
        },
      ],
      multiple: true,
      form: {
        title: "",
        areaName: "",
        status: "",
        orderNum: "",
        content: "",
        parentAreaName: "",
        imgUrl: "",
        videoUrl: "",
      },
      fileList: [],
      videoList: [],
      // 表单校验
      rules: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        areaName: [
          { required: true, message: "城市不能为空", trigger: "blur" },
        ],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
        orderNum: [
          { required: true, message: "显示顺序不能为空", trigger: "blur" },
        ],
        content: [{ required: true, message: "内容不能为空", trigger: "blur" }],
      },
      type: 1,
      cityList: [],
      city: [],
    };
  },
  created() {
    this.type = this.$route.query.type;
    this.form.id = this.$route.query.id || "";
    if (this.form.id) {
      this.getData();
    }
    this.getCityList();
  },
  methods: {
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    getData() {
      getDataById(this.form.id).then((res) => {
        this.type = res.data.type;
        this.form.title = res.data.title;
        this.form.areaName = res.data.areaName;
        this.form.status = res.data.status;
        this.form.orderNum = res.data.orderNum;
        this.form.content = res.data.content;
        this.form.parentAreaName = res.data.parentAreaName;
        this.form.imgUrl = res.data.imgUrl;
        this.form.videoUrl = res.data.videoUrl;
        this.city = res.data.parentAreaName
          ? [res.data.parentAreaName, res.data.areaName]
          : [res.data.areaName];
        this.fileList = [
          {
            name: res.data.imgUrl.split("/").pop(),
            url: res.data.imgUrl,
          },
        ];
        this.videoList = [
          {
            name: res.data.videoUrl.split("/").pop(),
            url: res.data.videoUrl,
          },
        ];
      });
    },
    getCityList() {
      cityList().then((res) => {
        this.cityList = res.data.map((item) => {
          return {
            value: item.cityName,
            label: item.cityName,
            children: item.countryNames.map((child) => {
              return {
                value: child,
                label: child,
              };
            }),
          };
        });
      });
    },
    handleChange(value) {
      this.city = value;
      this.form.parentAreaName = value.length > 1 ? value[0] : "";
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      const type = ["image/jpeg", "image/jpg", "image/png", "image/svg"];
      const isJPG = type.includes(file.type);
      // 检验文件格式
      if (!isJPG) {
        this.$message.error(`图片格式错误!`);
        return false;
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 < 500;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 500 KB!`);
          return false;
        }
      }
      return true;
    },
    handleRemove(file) {
      this.form.imgUrl = "";
    },
    handleRemoveVideo() {
      this.form.videoUrl = "";
    },
    handleBeforeUploadVideo(file) {
      const isVideo =
        file.type === "video/mp4" ||
        file.type === "video/x-msvideo" ||
        file.type === "video/quicktime";
      const isLt200M = file.size / 1024 / 1024 < 200;
      if (!isVideo) {
        this.$message.error("上传视频只能是 MP4, AVI, MOV 格式!");
      }
      if (!isLt200M) {
        this.$message.error("上传视频大小不能超过 200MB!");
      }
      return isVideo && isLt200M;
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleUploadSuccessVideo(res, file) {
      // 如果上传成功
      if (res.code == 200) {
        this.form.videoUrl = res.fileName;
      } else {
        this.$message.error("图片上传失败");
      }
    },
    handleUploadSuccess(res, file) {
      // 如果上传成功
      if (res.code == 200) {
        this.form.imgUrl = res.fileName;
        // this.$refs.upload.clearFiles();
      } else {
        this.$message.error("图片上传失败");
      }
    },
    // 取消按钮
    cancel() {
      this.$router.push("/index?type=" + this.type);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.type == 2) {
            if (!this.form.imgUrl) return this.$message.error("请上传图片");
          }
          const city = this.city.length > 1 ? this.city[1] : this.city[0];
          if (this.form.id) {
            editData({ ...this.form, areaName: city, type: this.type }).then(
              (response) => {
                this.$modal.msgSuccess("修改成功");
                this.$router.push("/index?type=" + this.type);
              }
            );
          } else {
            addData({ ...this.form, areaName: city, type: this.type }).then(
              (response) => {
                this.$modal.msgSuccess("新增成功");
                this.$router.push("/index?type=" + this.type);
              }
            );
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.w-100 {
  width: 100%;
}
.btnText {
  color: #0052d9 !important;
}
.dialogForm {
  // ::v-deep .el-form-item {
  //   margin-bottom: 10px;
  // }
  ::v-deep.el-form--label-top .el-form-item__label {
    padding: 0;
  }
}
.add {
  background: #0052d9;
  color: #fff;
  border: none;
}
.delBtn {
  background: #e7e7e7;
  color: #000;
  border: none;
}
.open {
  width: 52px;
  height: 32px;
  background: #e3f9e9;
  border-radius: 3px 3px 3px 3px;
  border: 1px solid #2ba471;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 400;
  font-size: 14px;
  color: #2ba471;
}
.close {
  width: 52px;
  height: 32px;
  background: #d8d8d8;
  border-radius: 3px 3px 3px 3px;
  border: 1px solid #767676;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 400;
  font-size: 14px;
  color: #767676;
}
.statusBox {
  width: 100%;
  display: flex;
  justify-content: center;
}
.img {
  width: 38px;
  height: 38px;
}
</style>
